package love.bot.forli.group.review.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.Api;
import love.bot.forli.group.review.bean.AuthInfo;
import love.bot.forli.group.review.bean.Result;
import love.bot.forli.group.review.bean.Vo.LoginVo;
import love.bot.forli.group.review.entity.AdminUser;
import love.bot.forli.group.review.interceptor.AuthenticationInterceptor;
import love.bot.forli.group.review.service.AdminUserService;
import love.bot.forli.group.review.util.BCrypt;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 无以铭川
 */
@Api(tags = "登录相关接口")
@RestController
public class LoginController {

    private final AdminUserService adminUserService;

    public LoginController(AdminUserService adminUserService) {
        this.adminUserService = adminUserService;
    }

    @PostMapping("/login")
    public Result<Object> login(@RequestBody LoginVo loginVo) throws NoSuchAlgorithmException {
        String username = loginVo.getUsername();
        AdminUser adminUser = adminUserService.getOne(Wrappers.lambdaQuery(AdminUser.class).eq(AdminUser::getUsername, username));
        if (adminUser == null) {
            return Result.fail("用户名不存在");
        }
        if (BCrypt.matches(loginVo.getPassword(), adminUser.getPassword())) {
            return Result.success("登录成功",
                    new AuthInfo(MD5Encoder.encode(MessageDigest.getInstance("MD5").digest((username + AuthenticationInterceptor.SALT).getBytes(StandardCharsets.UTF_8))),username));
        }
        return Result.fail("密码错误");
    }
}
